package com.test33_反射;

import org.junit.Test;

import java.lang.reflect.Constructor;

/**
 * 反射调用构造方法
 */
public class Demo06_Constructor {

    @Test
    public void test1() throws Exception {
        Class<?> clazz = Class.forName("com.test33_反射.Book6");
        {   // 获取public权限的构造方法
            System.out.println("-------------- getConstructors()获取构造 --------------");
            for (Constructor<?> constructor : clazz.getConstructors()) {
                System.out.println("【1 - 构造信息】" + constructor);
            }
        }
        {   // 可以获得类中全部的构造方法
            System.out.println("-------------- getDeclaredConstructors()获取构造 --------------");
            for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
                System.out.println("【2 - 构造信息】" + constructor);
            }
        }
    }

    /**
     * 获取有参构造方法，并进行实例化
     */
    @Test
    public void test2() throws Exception {
        Class<?> clazz = Class.forName("com.test33_反射.Book6");
        Constructor<?> constructor = clazz.getDeclaredConstructor(String.class, String.class, double.class);
        constructor.setAccessible(true);    // 设置允许访问
        Object obj = constructor.newInstance("Java从入门到项目实战", "李兴华", 99.8);  // 反射对象实例化
        System.out.println(obj);
    }
}

class Book6 {
    private String title;
    private String author;
    private double price;

    public Book6() {
    }

    protected Book6(String title) {
        this.title = title;
    }

    Book6(String title, String author) {
        this.title = title;
        this.author = author;
    }

    private Book6(String title, String author, double price) {
        this.title = title;
        this.author = author;
        this.price = price;
    }

    @Override
    public String toString() {
        return "【Book】名称：" + this.title + "、作者：" + this.author + "、价格：" + this.price;
    }
}
